//
//  PoiTableViewController.m
//  mpoi
//
//  Created by thomasho on 15/11/6.
//  Copyright © 2015年 thomasho. All rights reserved.
//

#import "PoiTableViewController.h"
#import "DBData.h"
#import "Foundation_defines.h"
#import "SVProgressHUD.h"
#import "NSDictionary+expanded.h"
@interface PoiTableViewController ()<UIAlertViewDelegate,UISearchBarDelegate>
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) NSArray *beaconArray;
@end

@implementation PoiTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [DBData Select:tb_relic Filelds:nil condition:SF(@"mid= '%@' order by mappath", [[[NSUserDefaults standardUserDefaults] valueForKey:@"floor"] valueForKey:@"id"])];
    self.beaconArray = [DBData Select:tb_beacon Filelds:nil condition:nil];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self reloadData];
}
- (void)reloadData{
    if (!self.dataArray.count) {
        NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:SF2(@"http://dev.apiservice.saidaoyou.com/v1/museum/spot/listbymus/%@?code=1766860453&token=%@",[[[NSUserDefaults standardUserDefaults] valueForKey:@"floor"] valueForKey:@"id"],[[NSUserDefaults standardUserDefaults] valueForKey:@"token"])]];
        if(data){
             id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
            if ([obj isKindOfClass:[NSArray class]]) {
                [DBData Delete:tb_relic condition:nil];
                [DBData ImportTb:tb_relic data:obj key:@"id"];
                for (NSDictionary *dict in obj) {
                    NSString *mappath = [dict valueForJSONStrKey:@"mappath"];
                    NSString *ext1 = [dict valueForJSONStrKey:@"ext1"];
                    if (mappath.length||ext1.length) {
                        //不得替换本地待更新的数据。
                        if(0==[[DBData Select:tb_beacon Filelds:nil condition:SF(@"id=%@ and status = 0",dict[@"id"])] count]){
                            [DBData InsertReplace:tb_beacon values:@{@"id":dict[@"id"],@"likeid":[[[NSUserDefaults standardUserDefaults] valueForKey:@"floor"] valueForKey:@"id"],@"b_mac":dict[@"ext2"]?:@"",@"g_name":dict[@"name"]?:@"",@"b_mm":ext1,@"xy":mappath,@"status":@"1"}];
                        }
                    }
                }

                self.dataArray = [DBData Select:tb_relic Filelds:nil condition:SF(@"mid= '%@' order by mappath", [[[NSUserDefaults standardUserDefaults] valueForKey:@"floor"] valueForKey:@"id"])];
                self.beaconArray = [DBData Select:tb_beacon Filelds:nil condition:nil];
            }else{
                [SVProgressHUD showErrorWithStatus:[obj valueForKey:@"msg"]];
            }
        }else{
            [[[UIAlertView alloc] initWithTitle:@"网络数据加载失败" message:nil delegate:self cancelButtonTitle:@"下次" otherButtonTitles:@"重试", nil] show];
        }
    }
    [self.tableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.cancelButtonIndex == buttonIndex) {
        self.dataArray = [DBData Select:tb_relic Filelds:nil condition:nil];
        [self.tableView reloadData];
    }else{
        [self reloadData];
    }
}

#pragma mark - Actions
- (IBAction)refreshButtonClicked:(id)sender {
    self.dataArray = nil;
    [self reloadData];
}
- (IBAction)beaconButtonClicked:(UIButton*)sender {
    [self performSegueWithIdentifier:@"beacon" sender:[self.dataArray objectAtIndex:sender.tag]];
}
#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list" forIndexPath:indexPath];
    NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [dict valueForKey:@"name"];
    NSArray *array = [DBData Select:tb_beacon Filelds:nil condition:SF(@"id = %@", [dict valueForKey:@"id"])];
    UILabel *lbl_xy = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *lbl_beacon = (UILabel *)[cell.contentView viewWithTag:100];
    [(UIButton*)cell.accessoryView setSelected:NO];
    lbl_beacon.text = @"";
    lbl_xy.text = @"";
    if (array.count&&[array.lastObject[@"xy"] length]) {
        lbl_xy.text = array.lastObject[@"xy"];
    }
    if (array.count&&[array.lastObject[@"b_mm"] length]) {
        lbl_beacon.text = array.lastObject[@"b_mm"];
        [(UIButton*)cell.accessoryView setSelected:YES];
    }
    cell.accessoryView.tag = indexPath.row;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"poi" object:
    NSDictionary *dict = self.dataArray[indexPath.row];
    [self.sender setTitle:[dict valueForKey:@"name"] forState:UIControlStateNormal];
    [self.sender setTag:[[dict valueForKey:@"id"] integerValue]+100];
    CGPoint pt = self.sender.center;

    NSDictionary *floor = [[NSUserDefaults standardUserDefaults] valueForKey:@"floor"];
    CGSize size = CGSizeFromString([floor valueForKey:@"size"]);
    NSDictionary *values = @{@"g_name":dict[@"name"]?:@"",@"xy":SF2(@"%0.2f,%0.2f", pt.x/size.width, pt.y/size.height),@"id":dict[@"id"],@"likeid":[floor valueForKey:@"id"],@"status":@"0"};
    NSDictionary *dic = [DBData Select:tb_beacon Filelds:nil condition:SF(@"id=%@", values[@"id"])].lastObject;
    if (dic) {
        [DBData Update:tb_beacon values:values condition:SF(@"id = %@", values[@"id"])];
    }else{
        [DBData InsertReplace:tb_beacon values:values];
    }
    [tableView reloadData];
}
- (NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"解除";
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle  == UITableViewCellEditingStyleDelete) {
        NSDictionary *dict = self.dataArray[indexPath.row];
        [self.sender setTitle:@"" forState:UIControlStateNormal];
        [self.sender setTag:999];
        [DBData Update:tb_beacon values:@{@"xy":@"",@"status":@"0"} condition:SF(@"id = %@", dict[@"id"])];
        [tableView reloadData];
    }
}

#pragma mark - UISearchBar
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self searchKey:searchText];
}
- (void)searchKey:(NSString*)key {
    self.dataArray = [DBData Select:tb_relic Filelds:nil condition:[NSString stringWithFormat:@"name like '%%%@%%'",key]];
    [self.tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

#pragma mark - prepareForSegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.destinationViewController respondsToSelector:@selector(setDataDict:)]) {
        [segue.destinationViewController setValue:sender forKey:@"dataDict"];
    }
}
@end
